package com.witmore.skyline.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.witmore.skyline.db.entity.DriverDO;
import com.witmore.skyline.db.entity.DeviceDO;
import com.witmore.skyline.db.mapper.DriverMapper;
import com.witmore.skyline.db.mapper.DeviceMapper;
import com.witmore.skyline.web.controller.vo.param.DriverAddParam;
import com.witmore.skyline.web.controller.vo.param.DriverDeleteParam;
import com.witmore.skyline.web.controller.vo.param.DriverListParamVO;
import com.witmore.skyline.web.controller.vo.result.*;
import com.witmore.skyline.web.service.DriverService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 驾驶员服务实现类
 * 
 * @author 豆子高
 * @since 2025-10-27
 */
@Slf4j
@Service
public class DriverServiceImpl implements DriverService {

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public ResponsePageResult<DriverResultVO> driverListPage(DriverListParamVO param) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<DriverDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DriverDO::getOrgId, param.getOrgId())
                   .eq(DriverDO::getIsDeleted, 0)
                   .eq(param.getProjectId() != null, DriverDO::getProjectId, param.getProjectId())
                   .eq(param.getStatus() != null, DriverDO::getStatus, param.getStatus())
                   .like(StringUtils.hasText(param.getDriverName()), DriverDO::getDriverName, param.getDriverName())
                   .like(StringUtils.hasText(param.getPhone()), DriverDO::getPhone, param.getPhone())
                   .like(StringUtils.hasText(param.getLicenseType()), DriverDO::getLicenseType, param.getLicenseType())
                   .orderByDesc(DriverDO::getCreateTime);

            // 分页查询
            Page<DriverDO> page = new Page<>(param.getPage(), param.getSize());
            Page<DriverDO> result = driverMapper.selectPage(page, wrapper);

            // 转换为VO
            List<DriverResultVO> voList = result.getRecords().stream()
                    .map(this::convertToResultVO)
                    .collect(Collectors.toList());

            // 查询绑定设备信息
            fillDeviceBindInfo(voList);

            PageInfo pageInfo = new PageInfo(result.getCurrent(), result.getSize(), result.getTotal(), result.getPages());
            return ResponsePageResult.success(voList, pageInfo);

        } catch (Exception e) {
            log.error("查询驾驶员列表失败", e);
            return ResponsePageResult.fail(500, "查询驾驶员列表失败");
        }
    }

    @Override
    public ResponseResult<Void> saveOrUpdate(DriverAddParam param) {
        try {
            if (param.getId() == null) {
                // 新增逻辑
                return addDriver(param);
            } else {
                // 编辑逻辑
                return updateDriver(param);
            }
        } catch (Exception e) {
            log.error("保存或更新驾驶员失败", e);
            return ResponseResult.fail(500, "保存或更新驾驶员失败");
        }
    }

    /**
     * 新增驾驶员
     */
    private ResponseResult<Void> addDriver(DriverAddParam param) {
        // 检查手机号是否已存在
        LambdaQueryWrapper<DriverDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DriverDO::getPhone, param.getPhone())
               .eq(DriverDO::getOrgId, param.getOrgId())
               .eq(DriverDO::getIsDeleted, 0);
        
        DriverDO existDriver = driverMapper.selectOne(wrapper);
        if (existDriver != null) {
            return ResponseResult.fail(400, "该手机号已存在");
        }

        // 创建驾驶员
        DriverDO driver = new DriverDO();
        BeanUtils.copyProperties(param, driver);
        driver.setOrgId(param.getOrgId());
        driver.setStatus(param.getStatus() != null ? param.getStatus() : (byte) 1); // 默认启用
        driver.setIsDeleted((byte) 0);
        driver.setCreateTime(LocalDateTime.now());
        driver.setUpdateTime(LocalDateTime.now());

        int result = driverMapper.insert(driver);
        if (result > 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(500, "新增驾驶员失败");
        }
    }

    /**
     * 更新驾驶员
     */
    private ResponseResult<Void> updateDriver(DriverAddParam param) {
        // 检查驾驶员是否存在
        DriverDO existDriver = driverMapper.selectById(param.getId());
        if (existDriver == null || existDriver.getIsDeleted() == 1) {
            return ResponseResult.fail(404, "驾驶员不存在");
        }

        // 检查手机号是否被其他驾驶员使用
        LambdaQueryWrapper<DriverDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DriverDO::getPhone, param.getPhone())
               .eq(DriverDO::getOrgId, existDriver.getOrgId())
               .eq(DriverDO::getIsDeleted, 0)
               .ne(DriverDO::getId, param.getId());
        
        DriverDO phoneExistDriver = driverMapper.selectOne(wrapper);
        if (phoneExistDriver != null) {
            return ResponseResult.fail(400, "该手机号已被其他驾驶员使用");
        }

        // 更新驾驶员信息
        DriverDO driver = new DriverDO();
        BeanUtils.copyProperties(param, driver);
        driver.setUpdateTime(LocalDateTime.now());

        int result = driverMapper.updateById(driver);
        if (result > 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(500, "修改驾驶员失败");
        }
    }

    @Override
    public ResponseResult<Void> delete(DriverDeleteParam param) {
        try {
            // 检查驾驶员是否存在
            DriverDO existDriver = driverMapper.selectById(param.getId());
            if (existDriver == null || existDriver.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "驾驶员不存在");
            }

            // 检查是否已绑定设备
            LambdaQueryWrapper<DeviceDO> deviceWrapper = new LambdaQueryWrapper<>();
            deviceWrapper.eq(DeviceDO::getDriverId, param.getId())
                        .eq(DeviceDO::getIsDeleted, 0);
            DeviceDO boundDevice = deviceMapper.selectOne(deviceWrapper);
            if (boundDevice != null) {
                return ResponseResult.fail(400, "该驾驶员已绑定设备，请先解绑后再删除");
            }

            // 逻辑删除
            DriverDO driver = new DriverDO();
            driver.setId(param.getId());
            driver.setIsDeleted((byte) 1);
            driver.setUpdateTime(LocalDateTime.now());

            int result = driverMapper.updateById(driver);
            if (result > 0) {
                return ResponseResult.success();
            } else {
                return ResponseResult.fail(500, "删除驾驶员失败");
            }

        } catch (Exception e) {
            log.error("删除驾驶员失败", e);
            return ResponseResult.fail(500, "删除驾驶员失败");
        }
    }

    @Override
    public ResponseResult<DriverResultVO> getDetail(Integer id) {
        try {
            DriverDO driver = driverMapper.selectById(id);
            if (driver == null || driver.getIsDeleted() == 1) {
                return ResponseResult.fail(404, "驾驶员不存在");
            }

            DriverResultVO vo = convertToResultVO(driver);
            
            // 查询绑定设备信息
            LambdaQueryWrapper<DeviceDO> deviceWrapper = new LambdaQueryWrapper<>();
            deviceWrapper.eq(DeviceDO::getDriverId, id)
                        .eq(DeviceDO::getIsDeleted, 0);
            DeviceDO boundDevice = deviceMapper.selectOne(deviceWrapper);
            if (boundDevice != null) {
                vo.setIsBound(true);
                vo.setBoundDeviceId(boundDevice.getId());
                vo.setBoundDeviceName(boundDevice.getDeviceName());
            } else {
                vo.setIsBound(false);
            }

            return ResponseResult.success(vo);

        } catch (Exception e) {
            log.error("查询驾驶员详情失败", e);
            return ResponseResult.fail(500, "查询驾驶员详情失败");
        }
    }

    @Override
    public ResponseResult<List<DriverSimpleVO>> getAvailableDriverList(Integer orgId) {
        try {
            // 查询未绑定设备的驾驶员
            LambdaQueryWrapper<DriverDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DriverDO::getOrgId, orgId)
                   .eq(DriverDO::getIsDeleted, 0)
                   .eq(DriverDO::getStatus, 1)
                   .orderByDesc(DriverDO::getCreateTime);

            List<DriverDO> drivers = driverMapper.selectList(wrapper);
            
            // 过滤掉已绑定设备的驾驶员
            List<Integer> driverIds = drivers.stream().map(DriverDO::getId).collect(Collectors.toList());
            if (!driverIds.isEmpty()) {
                LambdaQueryWrapper<DeviceDO> deviceWrapper = new LambdaQueryWrapper<>();
                deviceWrapper.in(DeviceDO::getDriverId, driverIds)
                            .eq(DeviceDO::getIsDeleted, 0);
                List<DeviceDO> boundDevices = deviceMapper.selectList(deviceWrapper);
                List<Integer> boundDriverIds = boundDevices.stream()
                        .map(DeviceDO::getDriverId)
                        .collect(Collectors.toList());

                drivers = drivers.stream()
                        .filter(driver -> !boundDriverIds.contains(driver.getId()))
                        .collect(Collectors.toList());
            }

            List<DriverSimpleVO> result = drivers.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());

            return ResponseResult.success(result);

        } catch (Exception e) {
            log.error("查询可用驾驶员列表失败", e);
            return ResponseResult.fail(500, "查询可用驾驶员列表失败");
        }
    }


    /**
     * 转换为结果VO
     */
    private DriverResultVO convertToResultVO(DriverDO driver) {
        DriverResultVO vo = new DriverResultVO();
        BeanUtils.copyProperties(driver, vo);
        
        // 设置状态名称
        if (driver.getStatus() != null) {
            vo.setStatusName(driver.getStatus() == 1 ? "启用" : "禁用");
        }
        
        return vo;
    }

    /**
     * 转换为简单VO
     */
    private DriverSimpleVO convertToSimpleVO(DriverDO driver) {
        DriverSimpleVO vo = new DriverSimpleVO();
        BeanUtils.copyProperties(driver, vo);
        return vo;
    }

    /**
     * 填充设备绑定信息
     */
    private void fillDeviceBindInfo(List<DriverResultVO> voList) {
        if (voList.isEmpty()) {
            return;
        }

        List<Integer> driverIds = voList.stream().map(DriverResultVO::getId).collect(Collectors.toList());
        
        LambdaQueryWrapper<DeviceDO> deviceWrapper = new LambdaQueryWrapper<>();
        deviceWrapper.in(DeviceDO::getDriverId, driverIds)
                    .eq(DeviceDO::getIsDeleted, 0);
        List<DeviceDO> boundDevices = deviceMapper.selectList(deviceWrapper);

        Map<Integer, DeviceDO> deviceMap = boundDevices.stream()
                .collect(Collectors.toMap(DeviceDO::getDriverId, device -> device));

        voList.forEach(vo -> {
            DeviceDO device = deviceMap.get(vo.getId());
            if (device != null) {
                vo.setIsBound(true);
                vo.setBoundDeviceId(device.getId());
                vo.setBoundDeviceName(device.getDeviceName());
            } else {
                vo.setIsBound(false);
            }
        });
    }
}
